//
//  AppDelegate.m
//  Meroad
//
//  Created by 郭孝通 on 2019/1/25.
//  Copyright © 2019 郭孝通 沈煜航. All rights reserved.
//

#import "AppDelegate.h"
#import "WebViewController.h"
#import "UserViewController.h"
#import "MapViewController.h"
#import "AccountViewController.h"

@interface AppDelegate ()<CustomDraverViewDelegate,UIGestureRecognizerDelegate,NSURLSessionDataDelegate>{
    
    //NSMutableData *_recvData;
}

@property (nonatomic) NSArray *uuidArray;
@property (nonatomic) MapViewController *mapViewController;
@property (nonatomic) WebViewController *webViewController;
@property (nonatomic) UserViewController *userViewController;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [AMapServices sharedServices].apiKey = @"5ba2e81d035c1e30c936986b32c91361";
    
    //将用户语言强制转成中文
    /*
     //用如下语句还原语言
    NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
     [[NSUserDefaults standardUserDefaults] setObject:userDefaultLanguages forKey:@"AppleLanguages"];
     */
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans", nil] forKey:@"AppleLanguages"];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    
    _mapViewController = [[MapViewController alloc] init];
    _webViewController = [[WebViewController alloc] init];
    _userViewController = [[UserViewController alloc] init];
    
    _tabBarController = [[UITabBarController alloc] init];
    _tabBarController.viewControllers = @[_webViewController,_mapViewController,_userViewController];
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
    [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    /*
    UIView* whiteView = [[UIView alloc] initWithFrame:CGRectMake(_tabBarController.tabBar.bounds.origin.x, _tabBarController.tabBar.bounds.origin.y - 7, _tabBarController.tabBar.bounds.size.width, _tabBarController.tabBar.bounds.size.height + 30)];
    [whiteView setBackgroundColor:[UIColor whiteColor]];
    [whiteView setAlpha:0];
    [_tabBarController.tabBar addSubview:whiteView];
     */
    
    CGRect tempRect = _tabBarController.tabBar.bounds;
    
    [_tabBarController.tabBar setFrame:CGRectMake(tempRect.origin.x, tempRect.origin.y - 7, _tabBarController.tabBar.bounds.size.width, tempRect.size.height + 24)];
    
    [_tabBarController.tabBar setBackgroundColor:[UIColor whiteColor]];
    
    CustomTabBar *tabBar = [[CustomTabBar alloc] initWithFrame:CGRectMake(tempRect.origin.x, tempRect.origin.y - 7, tempRect.size.width, tempRect.size.height + 7)];
    
    
    tabBar.tabBarItemAttributes = @[
                                    @{kCustomTabBarItemAttributeTitle : @"看 点", kCustomTabBarItemAttributeNormalImageName : @"news_normal",kCustomTabBarItemAttributeSelectedImageName : @"news_selected", kCustomTabBarItemAttributeType : @(CustomTabBarItemNormal)},
                                    @{kCustomTabBarItemAttributeTitle : @"导 航", kCustomTabBarItemAttributeNormalImageName : @"map_normal",kCustomTabBarItemAttributeSelectedImageName : @"map_selected", kCustomTabBarItemAttributeType : @(CustomTabBarItemNormal)},
                                    @{kCustomTabBarItemAttributeTitle : @"我 的", kCustomTabBarItemAttributeNormalImageName : @"user_normal",kCustomTabBarItemAttributeSelectedImageName : @"user_selected", kCustomTabBarItemAttributeType : @(CustomTabBarItemNormal)}];
    
    tabBar.delegate = self;

    [_tabBarController.tabBar addSubview:tabBar];
    self.window.rootViewController = _tabBarController;
    
    self.tabBarViewHeight = tabBar.bounds.size.height;
    
    [[[_tabBarController.tabBar subviews] lastObject] setSelectedIndex:1];
    
    //抽屉View
    self.draverView = [CustomDraverView draverView];
    self.draverView.delegate = self;
    [self.tabBarController.view insertSubview:self.draverView atIndex:self.tabBarController.view.subviews.count - 1];
    //[self.tabBarController.view bringSubviewToFront:self.tabBarController.tabBar];
    
    UISwipeGestureRecognizer* swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(showDraver)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.window addGestureRecognizer:swipe];
    swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideDraver)];
    swipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.window addGestureRecognizer:swipe];
    
    //开辟多线程存放定时器
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(timerThread) object:nil];
    [thread start];
    
    //NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
    
    //[NSThread sleepForTimeInterval:1];
    
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self saveData];
}

//保存本地数据
-(void)saveData{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    if(self.userModel.userHeaderImage){
        NSData *_data = UIImageJPEGRepresentation(self.userModel.userHeaderImage, 1.0f);
        //将图片的data转化为字符串
        NSString *strimage64 = [_data base64EncodedStringWithOptions:0];
        //[[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
        [dict setValue:strimage64 forKey:@"userHeaderImage"];
    }
    if(self.userModel.userName){
        [dict setValue:self.userModel.userName forKey:@"userName"];
    }
    if(self.userModel.cookie){
        [dict setValue:self.userModel.cookie forKey:@"cookie"];
    }
    if(self.userModel.userName){
        [dict setValue:self.userModel.userName forKey:@"userName"];
    }
    if(self.userModel.userAge){
        [dict setValue:self.userModel.userAge forKey:@"userAge"];
    }
    if(self.userModel.userType){
        [dict setValue:self.userModel.userType forKey:@"userType"];
    }
    if(self.userModel.userBirth){
        [dict setValue:self.userModel.userBirth forKey:@"userBirth"];
    }
    if(self.userModel.userGender){
        [dict setValue:self.userModel.userGender forKey:@"userGender"];
    }
    if(self.userModel.userTel){
        [dict setValue:self.userModel.userTel forKey:@"userTel"];
    }
    if(self.userModel.userEmail){
        [dict setValue:self.userModel.userEmail forKey:@"userEmail"];
    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistpath = [paths objectAtIndex:0];
    NSString *filename=[plistpath stringByAppendingPathComponent:@"userInfo.plist"];
    NSDictionary* tempDict = [NSDictionary dictionaryWithContentsOfFile:filename];
    if(tempDict==nil){
        NSFileManager* fm = [NSFileManager defaultManager];
        [fm createFileAtPath:filename contents:nil attributes:nil];
    }
    
    //写入内容
    [dict writeToFile:filename atomically:YES];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
//    [[[tabBarController.tabBar subviews] lastObject] setSelectedIndex:1];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma thread

-(void)timerThread{
    @autoreleasepool {
        NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    }
}






#pragma timer

- (void)updateTimer{
    static int num = 0;
    
    if(self.uuidArray == nil){
        [self uuidGet];
    }
    
    
    if(num == 0){
        [self uuidGet];
    }
    
    if(num & 1){
        [self toiletGet];
    }
    else{
        [self toiletsSorting];
    }
    
    if(self.userModel.address == nil || [self.userModel.address isEqualToString:@""]){
        [self.userModel initialAddress];
    }
    
    num = num>60?0:num+1;
}

- (void)uuidGet{
    //获取附近厕所的uuid
    
    NSURL *url = [NSURL URLWithString:@"http://101.132.181.191/meroad/public/index.php/toilet/getAllUuid"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.timeoutInterval = 5.0;
    request.HTTPMethod = @"POST";
    
    [request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];
    [request setValue:[NSString stringWithFormat:@"%f",self.userModel.location.coordinate.longitude] forHTTPHeaderField:@"longitude"];
    [request setValue:[NSString stringWithFormat:@"%f",self.userModel.location.coordinate.latitude] forHTTPHeaderField:@"latitude"];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    //NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    
    NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error == nil){
            NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            NSLog(@"%@",json);
            NSLog(@"%@",[json valueForKey:@"errorMsg"]);
            
            self.uuidArray = [json valueForKey:@"data"];
            NSLog(@"%@",self.uuidArray);
        }
        else{
            NSLog(@"请求失败！");
        }
    }];
    
    [dataTask resume];
    
}

- (void)toiletGet{
    //用uuid获取厕所信息
    for(NSString *str in self.uuidArray){
        NSURL *url = [NSURL URLWithString:@"http://101.132.181.191/meroad/public/index.php/toilet/getDetail"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.timeoutInterval = 5.0;
        request.HTTPMethod = @"POST";
        
        [request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];
        [request setValue:str forHTTPHeaderField:@"uuid"];
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        
        //NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
        
        NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if(error == nil){
                NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                NSLog(@"%@",json);
                NSLog(@"%@",[json valueForKey:@"errorMsg"]);
                
                NSDictionary *dict = [json valueForKey:@"data"];
                ToiletModel *newModel = [ToiletModel modelWithDict:dict];
                
                for(int i=0;i<self.toiletModels.count;i++){
                    ToiletModel *model = [self.toiletModels objectAtIndex:i];
                    //先刷新所有空的address
                    if(model.address == nil || [model.address isEqualToString:@""]){
                        [model initialAddress];
                    }
                    if([model.uuid isEqualToString:newModel.uuid]){
                        if([model isEqual:newModel]){
                            if(model.address == nil || [model.address isEqualToString:@""]){
                                [model initialAddress];
                            }
                            return;
                        }
                        [model initWithToiletModel:newModel];
                        //[self.toiletModels replaceObjectAtIndex:i withObject:newModel];
                        [self.mapViewController refreshOnePoint:i];
                        return;
                    }
                }
                [self.toiletModels addObject:newModel];
                [self.mapViewController addOnePoint:self.toiletModels.count - 1];
            }
            else{
                NSLog(@"请求失败！");
            }
        }];
        
        [dataTask resume];
    }
}


- (void) toiletsSorting{
    if(_toiletModels == nil){
        return;
    }
    
    NSArray *result = [_toiletModels sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        ToiletModel *model1 = (ToiletModel*) obj1;
        ToiletModel *model2 = (ToiletModel*) obj2;
        
        CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:model1.latitude longitude:model1.longitude];
        double distant1 = [self.userModel.location distanceFromLocation:loc1];
        double weight1 = -model1.spareHolesNumber * 15 + distant1;
        model1.distant = distant1;
        
        CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:model2.latitude longitude:model2.longitude];
        double distant2 = [self.userModel.location distanceFromLocation:loc2];
        double weight2 = -model2.spareHolesNumber * 15 + distant2;
        model2.distant = distant2;
        
        return weight1 >= weight2;
    }];
    
    for(int i = 0;i < result.count;i++){
        ToiletModel *model = [result objectAtIndex:i];
        model.sortResult = i+1;
    }
    
}


#pragma draverViewDelegate

- (void)draverViewDidSelectRowNumber:(NSInteger)num{
    
    UIAlertController* locationAlertController = [UIAlertController alertControllerWithTitle:@"当前位置" message:self.userModel.address preferredStyle:UIAlertControllerStyleAlert];
    UIAlertController* alertController = [UIAlertController alertControllerWithTitle:@"产品demo" message:@"该功能暂未上线" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertController* updateAlertController = [UIAlertController alertControllerWithTitle:@"检查更新" message:@"暂无更新" preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"确定");
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [updateAlertController addAction:okAction];
    [alertController addAction:okAction];
    [locationAlertController addAction:okAction];
    
    //num是选中的抽屉view中的行号
    //在此代理方法中进行跳转/关闭抽屉view
    NSLog(@"点击了第%ld行",num);
    [self.draverView hide];
    switch (num) {
        case 0:
            [[[_tabBarController.tabBar subviews] lastObject] setSelectedIndex:2];
            [self tabbarDidSelected:2];
            break;
        case 1:
            [self.window.rootViewController presentViewController:locationAlertController animated:YES completion:nil];
            break;
        case 2:
            [self.window.rootViewController presentViewController:updateAlertController animated:YES completion:nil];
            break;
            
        default:
            [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    }
    
}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}


#pragma gesture

-(void)showDraver{
    [self.draverView show];
}

-(void)hideDraver{
    [self.draverView hide];
}



#pragma 重写get方法

- (UserModel *)userModel{
    if(_userModel == nil){
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *plistpath = [paths objectAtIndex:0];
        NSString *filename=[plistpath stringByAppendingPathComponent:@"userInfo.plist"];
        NSMutableDictionary* tempDict = [NSMutableDictionary dictionaryWithContentsOfFile:filename];
        //NSLog(@"%@",tempDict);
        //NSData *data = [SYHDataArchiver dataForKey:@"userInfo"];
        if(tempDict == nil){
            _userModel = [UserModel modelWithDict:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InitialUserInfo.plist" ofType:nil]]];
        }
        else{
            /*
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSData *tempData = [SYHDataArchiver dataForKey:@"userHeaderImage"];
            UIImage *tempImage = [UIImage imageWithData:tempData];
            [dict setValue:tempImage forKey:@"userHeaderImage"];
             */
            
            NSData *_decodedImageData = [[NSData alloc]initWithBase64EncodedString:[tempDict objectForKey:@"userHeaderImage"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
            UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
            
            [tempDict setValue:_decodedImage forKey:@"userHeaderImage"];
            
            _userModel = [UserModel modelWithDict:tempDict];
        }
        
        [_userModel beginGettingLocation];
    }
    return _userModel;
}

- (NSArray *)toiletModels{
    if(_toiletModels == nil){
        /*
        NSArray* dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InitialToiletsInfo.plist" ofType:nil]];
        NSMutableArray* tempArray = [NSMutableArray array];
        for(NSDictionary* dict in dictArray){
            ToiletModel* model = [ToiletModel modelWithDict:dict];
            [tempArray addObject:model];
        }
        _toiletModels = tempArray;
         */
        _toiletModels = [[NSMutableArray alloc] init];
        [self updateTimer];
    }
    return _toiletModels;
}

#pragma delegate
//下一步应该改为进入 App 后未登录用户先登录，这里删除
- (void)tabbarDidSelected:(NSInteger)index{
    if(index == 2){
        if(self.userModel.cookie == nil){
            [self.window.rootViewController presentViewController:[[AccountViewController alloc] init]
                                                         animated:YES
                                                       completion:nil];
        }

    }
}

#pragma others

- (void)hideTabbar:(CustomTabBar *)tabbar
{
    if(tabbar.hidden == YES){
        return;
    }else{
        tabbar.hidden = YES;
    }
}

- (void)showTabBar:(CustomTabBar *)tabbar
{
    if(tabbar.hidden == YES){
        tabbar.hidden = NO;
    }else{
        return;
    }
}

-(instancetype)getTabbar
{
    return (AppDelegate *)_tabBarController.tabBar;
}



@end
